package com.itheima.leetcode;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * 合并多个有序链表
 *
 * @FileName E07LeetCode23
 * @Description
 * @Author Sword
 * @date 2025-04-24
 **/
public class E07LeetCode23 {

    public static ListNode mergeTwoLists(ListNode p1, ListNode p2) {
        ListNode s = new ListNode(-1, null);
        ListNode p = s;

        while (p1 != null && p2 != null) {
            if (p1.val < p2.val) {
                p.next = p1;
                p1 = p1.next;
            } else {
                p.next = p2;
                p2 = p2.next;
            }
            p = p.next;
        }

        if (p1 != null) {
            p.next = p1;
        }

        if (p2 != null) {
            p.next = p2;
        }

        return s.next;
    }


    public static ListNode mergeKLists(ListNode[] lists) {
        if (lists.length == 0) {
            return null;
        }
        return split(lists, 0, lists.length - 1);
    }

    /**
     * 返回合并后的链表
     *
     * @param lists
     * @param i     左边界
     * @param j     右边界
     * @return
     */
    private static ListNode split(ListNode[] lists, int i, int j) {
        if (i == j) {   //数组内只有一个链表
            return lists[i];
        }
        int m = (i + j) >>> 1;
        ListNode left = split(lists, i, m);
        ListNode right = split(lists, m + 1, j);
        return mergeTwoLists(left, right);
    }

    //Divide and Conquer 分而治之（分、治、合）
    //Decrease and conquer 减而治之

    public static void main(String[] args) {
        ListNode[] lists = {ListNode.of(1, 4, 5),
                ListNode.of(1, 3, 4),
                ListNode.of(2, 6)};

        ListNode merged = mergeKLists(lists);
        System.out.println(merged);
    }
}
